#include "FMODSystem.h"

#include "api/inc/fmod.hpp"
#include "api/inc/fmod_errors.h"
#include "wincompat.h"
#include <stdio.h>
#include <stdlib.h>
#include <iostream>

namespace SnackBreak
{
namespace Impl
{

System theFMODSystem;

void ERRCHECK(FMOD_RESULT result)
{
    if (result != FMOD_OK)
    {
        printf("FMOD error! (%d) %s\n", result, FMOD_ErrorString(result));
        exit(-1);
    }
};

System::System()
{
	FMOD_RESULT       result;

	result = FMOD::System_Create(&fmodsystem);
	ERRCHECK(result);

	unsigned int      version;
	result = fmodsystem->getVersion(&version);
	ERRCHECK(result);

	if (version < FMOD_VERSION)
	{
		printf("Error!  You are using an old version of FMOD %08x.  This program requires %08x\n", version, FMOD_VERSION);
		getch();
	}

	int maxChannels = 128; 
	result = fmodsystem->init(maxChannels, FMOD_INIT_NORMAL, 0);
	ERRCHECK(result);

	sampleRate = 44100.0;
	int srate;
	fmodsystem->getSoftwareFormat(&srate, 0,0,0,0,0);
	if (srate != 0)
		sampleRate = srate;
};

System::~System()
{
	std::cerr << "freeing system" << std::endl;
	FMOD_RESULT       result;
	result = fmodsystem->close();
	ERRCHECK(result);
	result = fmodsystem->release();
	ERRCHECK(result);
};

FMOD::System& System::Get()
{
	return *(theFMODSystem.fmodsystem);
}

double System::getSampleRate()
{
	return theFMODSystem.sampleRate;
}

}; // namespace Impl
}; // namespace SnackBreak

